package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.support.collections.DefaultRedisList;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements Ilock{

    private String name;//锁的名称
    private StringRedisTemplate stringRedisTemplate;
    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }
    //锁的前缀
    private static final String KEY_PREFIX = "lock:";

    //设置当前线程id防止误删锁的情况
    private static final String ID_PREFIX= UUID.fastUUID().toString(true)+"-";
    //初始化文件提高效率
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));//相对路劲获取文件
        UNLOCK_SCRIPT.setResultType(Long.class);//返回结果类型
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        //获取当前线程的id
        String TreadId = ID_PREFIX+ Thread.currentThread().getId();
        //获取锁
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name,
                TreadId,timeoutSec, TimeUnit.SECONDS);

        return Boolean.TRUE.equals(flag);//使用常量值判断当前返回值是否为空，防止拆箱的是否出现空指针异常，：拆箱：包装类转为器对应基本类型
    }

    @Override
    public void unLock() {//满足Redis的事务原子性防止极端情况下（在判断的时候发生堵塞导致删除别人的锁，造成线程安全）误删锁
        //调用lua脚本文件
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),//当前线程锁的key
                ID_PREFIX+Thread.currentThread().getId());//当前线程标识

    }



  /*  @Override
    public void unLock() {
        //获取当前线程标识
        String TreadId = ID_PREFIX+ Thread.currentThread().getId();

        //获取Redis中的存的当前线程的key
        String treadId = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);

        //判断当前线程的id是否一致，一致就删除掉
        if (TreadId.equals(treadId)) {
            //释放锁
            stringRedisTemplate.delete(KEY_PREFIX + name);

        }
    }*/
}
